<script module lang="ts">
    import { defineMeta } from "@storybook/addon-svelte-csf";
    import Form from "./Form.svelte";
    import { Checkbox } from "../Checkbox";
    import { Space } from "../Space";
    import FormItem from "../FormItem/FormItem.svelte";
    import { Input } from "../Input";
    import { RadioGroup } from "../RadioGroup";
    import Button from "../Button/Button.svelte";
    import { Modal } from "../Modal";
    import { Select } from "../Select";
    import FormItemRest from "../FormItemRest/FormItemRest.svelte";
    import CustomField from "./CustomField.svelte";
    import { Cascader } from "../Cascader";
    import { CheckboxGroup } from "../CheckboxGroup";
    import { ColorPicker } from "../ColorPicker";
    import { Datepicker } from "../Datepicker";
    import dayjs from "dayjs";
    import { Rate } from "../Rate";
    import Icon from "@iconify/svelte";
    import { Slider } from "../Slider";
    import { Spinner } from "../Spinner";
    import { Switch } from "../Switch";
    import { TreeSelect } from "../TreeSelect";
    import { Text } from "../Typography";

    const { Story } = defineMeta({
        title: "Components/Form/Form",
        component: Form,
        subcomponents: {
            FormItem,
            FormItemRest,
        },
        tags: ["autodocs"],
        argTypes: {
            margin: {
                table: {
                    defaultValue: { summary: "24" },
                },
            },
        },
        args: {},
    });

    let value = $state<string>("#19be6b");
    let form1: any;
    let formData11 = $state({
        name: "",
        password: "",
    });
    let formData1 = $state({
        name: "",
        password: "",
    });
    const formData = $state({
        type: "phone",
        value: "",
    });
    let modalVisible = $state(false);

    const formData2 = $state({
        period: "1",
        value: "",
    });

    const formData3 = $state({
        list: [""],
    });
    const formData4 = $state({
        list: [{ key: "", value: "" }],
    });

    const formData5 = $state({
        value: [],
    });

    const formData6 = $state({
        text: "",
        select: "",
        selectMulti: [],
        cascader: [],
        cascaderMulti: [],
        check: false,
        checkbox: [],
        radio: "",
        color: "",
        date: dayjs(),
        daterange: [],
        rate: 0,
        slider: 30,
        spinner: "",
        switch: "",
        tree: [],
    });

    const treeData = [
        {
            id: "beijing",
            title: "北京",
            children: [
                { id: "gugong", title: "故宫" },
                { id: "tiantan", title: "天坛" },
            ],
        },
        {
            id: "zhejiang",
            title: "浙江",
            children: [
                { id: "xihu", title: "西湖" },
                { id: "linyin", title: "灵隐" },
            ],
        },
    ];
    let form4: any;
    let form6: any;
</script>

<script lang="ts">
    $effect(() => {
        $inspect(formData4);
    });
</script>

<Story name="Default">
    {#snippet template(args)}
        <Form model={formData11}>
            <FormItem name="name" label="Username">
                <Input bind:value={formData11.name} />
            </FormItem>
        </Form>
    {/snippet}
</Story>

<Story name="WithRule">
    {#snippet template(args)}
        <Form model={formData1} bind:this={form1}>
            <FormItem
                name="name"
                label="Username"
                rules={[
                    { required: true, message: "Please input your username!" },
                    { max: 5, message: "最大长度5个字符", trigger: "input" },
                ]}
            >
                <Input bind:value={formData1.name} />
            </FormItem>
        </Form>
        <Button
            onclick={async () => {
                form1.resetFields();
            }}>重置</Button
        >
    {/snippet}
</Story>

<Story name="Inline">
    {#snippet template(args)}
        <Form model={formData1} inline>
            <FormItem name="name" label="用户名" rules={[{ required: true, message: "请输入用户名！" }]}>
                <Input bind:value={formData1.name} />
            </FormItem>
            <FormItem name="password" label="密码" rules={[{ required: true, message: "请输入密码！" }]}>
                <Input bind:value={formData1.password} />
            </FormItem>
        </Form>
    {/snippet}
</Story>

<!-- Margin 设置为0的时候 错误提示最好使用`errorTransfer` -->
<Story name="Margin">
    {#snippet template(args)}
        <Form model={formData1} margin={0} errorTransfer errorAlign="bottomLeft">
            <FormItem name="name" label="用户名" rules={[{ required: true, message: "请输入用户名！" }]}>
                <Input bind:value={formData1.name} />
            </FormItem>
            <Text disabled>提示信息提示信息提示信息提示信息</Text>
        </Form>
    {/snippet}
</Story>

<Story name="dynamicrule">
    {#snippet template(args)}
        <Form model={formData} labelWidth={80}>
            <FormItem name="type" label="选项">
                <RadioGroup
                    data={[
                        { label: "手机号验证", value: "phone" },
                        { label: "邮箱验证", value: "email" },
                    ]}
                    bind:value={formData.type}
                ></RadioGroup>
            </FormItem>
            <FormItem
                name="value"
                label={formData.type === "phone" ? "手机号" : "邮箱"}
                rules={formData.type === "phone" ? [{ pattern: /^1[3456789]\d{9}$/, message: "请输入正确的手机号" }] : [{ required: true, type: "email", message: "请输入正确的邮箱" }]}
            >
                <Input bind:value={formData.value} />
            </FormItem>
        </Form>
    {/snippet}
</Story>

<Story name="ErrorTip">
    {#snippet template(args)}
        <Button onclick={() => (modalVisible = true)}>打开</Button>
        <Modal bind:visible={modalVisible} title="测试">
            <Form model={formData1} errorTransfer>
                <FormItem name="name" label="Username" rules={[{ required: true, message: "Please input your username!" }]}>
                    <Input bind:value={formData1.name} />
                </FormItem>
            </Form>
        </Modal>
    {/snippet}
</Story>

<Story name="multi">
    {#snippet template(args)}
        <Form model={formData2} style="width: 400px;">
            <FormItem name="value" label="告警时间" rules={[{ required: true, message: "请选择告警时间！" }]}>
                <Space>
                    <FormItem name="period" style="flex: 0 0 100px;">
                        <Select
                            bind:value={formData2.period}
                            data={[
                                { value: "1", label: "每日" },
                                { value: "2", label: "每周" },
                                { value: "3", label: "每月" },
                            ]}
                        />
                    </FormItem>
                    <Input bind:value={formData2.value} />
                </Space>
            </FormItem>
        </Form>

        <Form model={formData2} style="width: 400px;">
            <FormItem name="value" label="告警时间" rules={[{ required: true, message: "请选择告警时间！" }]}>
                <Space>
                    <FormItemRest>
                        <Select
                            bind:value={formData2.period}
                            style="flex: 0 0 100px;"
                            data={[
                                { value: "1", label: "每日" },
                                { value: "2", label: "每周" },
                                { value: "3", label: "每月" },
                            ]}
                        />
                    </FormItemRest>
                    <Input bind:value={formData2.value} />
                </Space>
            </FormItem>
        </Form>

        <Form model={formData5} style="width: 400px;">
            <FormItem name="value" label="告警时间" rules={[{ required: true, message: "请设置告警时间！" }]}>
                <CustomField bind:value={formData5.value} />
            </FormItem>
        </Form>
    {/snippet}
</Story>

<Story name="list">
    {#snippet template(args)}
        <Form model={formData3} style="width: 400px;">
            {#each formData3.list as item, index (index)}
                <FormItem name={["list", index]} label="选项" rules={[{ required: true, message: "请填写选项！" }]}>
                    <Input bind:value={formData3.list[index]} />
                </FormItem>
            {/each}
        </Form>
        <Button onclick={() => formData3.list.push("")}>添加</Button>
    {/snippet}
</Story>

<Story name="list2">
    {#snippet template(args)}
        <Form
            bind:this={form4}
            model={formData4}
            style="width: 400px;"
            onchange={(n, v) => console.log(n, v)}
            onfinish={() => console.log("form pass...")}
            onfinishfailed={() => console.log("form validate failed...")}
            onsubmit={() => console.log("form submited...")}
        >
            {#each formData4.list as item, index (index)}
                <Space>
                    <FormItem
                        name={["list", index, "key"]}
                        label="编码"
                        rules={[
                            { required: true, message: "请填写编码！" },
                            { type: "string", max: 5, message: "编码长度不能超过5个字符" },
                        ]}
                    >
                        <Input bind:value={formData4.list[index].key} />
                    </FormItem>
                    <FormItem name={["list", index, "value"]} label="编码值" rules={[{ required: true, message: "请填写编码值！" }]}>
                        <Input bind:value={formData4.list[index].value} />
                    </FormItem>

                    <Button onclick={() => formData4.list.splice(index, 1)}>删除</Button>
                </Space>
            {/each}
        </Form>
        <Button onclick={() => formData4.list.push({ key: "", value: "" })}>添加</Button>
        <Button
            onclick={async () => {
                form4
                    .validate()
                    .then(() => {
                        console.log("success");
                    })
                    .catch((errors: any) => {
                        console.error(errors);
                    });
            }}>校验</Button
        >
        <Button
            onclick={async () => {
                form4
                    .validateFields([["list", 0, "key"]])
                    .then(() => {
                        console.log("success");
                    })
                    .catch((errors: any) => {
                        console.error(errors);
                    });
            }}>校验2</Button
        >

        <Button
            onclick={async () => {
                form4.clearValidate();
            }}>清除校验</Button
        >

        <Button
            onclick={async () => {
                form4.resetFields();
            }}>重置</Button
        >

        <Button
            onclick={async () => {
                form4.resetFields([["list", 0, "key"]]);
            }}>重置指定字段</Button
        >

        <Button
            onclick={async () => {
                form4.resetFields([["list", 0, "key"]], {
                    list: [{ key: "2" }],
                });
            }}>重置携带默认数据</Button
        >
    {/snippet}
</Story>

<Story name="Elements">
    {#snippet template(args)}
        <Form model={formData6} bind:this={form6} onchange={(n, v) => console.log(n, v)} colon={false}>
            <FormItem name="text" label="TEXT" rules={[{ required: true, message: "请输入Text！" }]}>
                <Input bind:value={formData6.text} placeholder="请输入" maxLength={10} clearable />
            </FormItem>
            <FormItem name="select" label="SELECT" rules={[{ required: true, message: "请选择！" }]}>
                <Select
                    bind:value={formData6.select}
                    placeholder="请选择"
                    clearable
                    data={[
                        { label: "选项1", value: 1 },
                        { label: "选项2", value: 2 },
                    ]}
                />
            </FormItem>
            <FormItem name="selectMulti" label="SELECTMULTI" rules={[{ required: true, message: "请选择！" }]}>
                <Select
                    bind:value={formData6.selectMulti}
                    multi
                    clearable
                    placeholder="请选择"
                    data={[
                        { label: "选项1", value: 1 },
                        { label: "选项2", value: 2 },
                        { label: "选项3", value: 3 },
                    ]}
                />
            </FormItem>

            <FormItem name="cascader" label="CASCADER" rules={[{ required: true, message: "请选择！" }]}>
                <Cascader
                    bind:value={formData6.cascader}
                    placeholder="请选择"
                    clearable
                    data={[
                        { title: "选项1", value: 1, children: [{ title: "选项1-1", value: 1.1 }] },
                        { title: "选项2", value: 2 },
                        { title: "选项3", value: 3 },
                    ]}
                />
            </FormItem>

            <FormItem name="cascaderMulti" label="CASCADERMULTI" rules={[{ required: true, message: "请选择！" }]}>
                <Cascader
                    bind:value={formData6.cascaderMulti}
                    multi
                    placeholder="请选择"
                    clearable
                    data={[
                        { title: "选项1", value: 1, children: [{ title: "选项1-1", value: 1.1 }] },
                        { title: "选项2", value: 2 },
                        { title: "选项3", value: 3 },
                    ]}
                />
            </FormItem>

            <FormItem name="check" label="CHECK">
                <Checkbox bind:checked={formData6.check} label="选项1" />
            </FormItem>

            <FormItem name="checkbox" label="CHECKBOX" rules={[{ required: true, message: "请选择！" }]}>
                <CheckboxGroup
                    bind:value={formData6.checkbox}
                    data={[
                        { label: "选项1", value: 1 },
                        { label: "选项2", value: 2 },
                        { label: "选项3", value: 3 },
                    ]}
                />
            </FormItem>

            <FormItem name="radio" label="RADIO" rules={[{ required: true, message: "请选择！" }]}>
                <RadioGroup
                    bind:value={formData6.radio}
                    placeholder="请选择"
                    data={[
                        { label: "选项1", value: 1 },
                        { label: "选项2", value: 2 },
                        { label: "选项3", value: 3 },
                    ]}
                />
            </FormItem>

            <FormItem name="color" label="COLOR" rules={[{ required: true, message: "请选择！" }]}>
                <ColorPicker bind:value={formData6.color} placeholder="请选择" />
            </FormItem>

            <FormItem name="date" label="日期" rules={[{ required: true, message: "请选择！" }]}>
                <Datepicker bind:value={formData6.date} placeholder="请选择" clearable />
            </FormItem>
            <FormItem name="daterange" label="DATERANGE" rules={[{ required: true, message: "请选择！" }]}>
                <Datepicker type="dateRange" bind:value={formData6.daterange} placeholder="请选择" clearable />
            </FormItem>
            <FormItem name="rate" label="RATE" rules={[{ required: true, message: "请选择！" }]}>
                <Rate bind:value={formData6.rate}>
                    {#snippet icon()}
                        <Icon icon="mdi:star" width={24} height={24} />
                    {/snippet}
                </Rate>
            </FormItem>
            <FormItem name="slider" label="SLIDER" rules={[{ required: true, message: "请选择！" }]}>
                <Slider bind:value={formData6.slider}></Slider>
            </FormItem>
            <FormItem name="spinner" label="SPINNER" rules={[{ required: true, message: "请选择！" }]}>
                <Spinner bind:value={formData6.spinner}></Spinner>
            </FormItem>
            <FormItem name="switch" label="SWITCH" rules={[{ required: true, message: "请选择！" }]}>
                <Switch bind:checked={formData6.switch}></Switch>
            </FormItem>
            <FormItem name="tree" label="TREE" rules={[{ required: true, message: "请选择！" }]}>
                <TreeSelect bind:value={formData6.tree} multi data={treeData} placeholder="请选择"></TreeSelect>
            </FormItem>

            <Button type="primary" onclick={() => form6.validate()}>验证</Button>
        </Form>
    {/snippet}
</Story>
